package org.soarsky.wealthchengdu.google.map;



import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class BaiduLocation{
	
	private static final String TAG = "BaiduLocation";
	
	public final static int GPS_LOC = 61;
	public final static int NET_LOC = 161;
	private static final int STOPTIMER = 20;
	
	private boolean mIsGps = false;
	private boolean isLocated = false;
	
	private LocationClient mLocationClient = null;
	private Context mContext;
	private BDLocation location=null;
	private boolean mStopThread = false;
	private IGetLocation mGetLocation;
	
	public interface IGetLocation{
		void successful(BDLocation loca);//成功
		void overTimeDo();//超时
		void failure();//失败
	}
	public void setCallBack(IGetLocation getLocatin){
		mGetLocation=getLocatin;
	}
	public BaiduLocation(final Context mCon) {
		this.mContext = mCon;
	
		mLocationClient = new LocationClient(mContext);
		LocationClientOption option = new LocationClientOption();

		option.setOpenGps(true);   //打开gps
		option.disableCache(true); //禁用缓存定位
		option.setCoorType("bd09ll"); // 设置坐标类型为bd09ll
		option.setPriority(LocationClientOption.GpsFirst); // 设置网络优先
		option.setProdName("elderLauncher");  // 设置产品线名称
		option.setScanSpan(1000);           //定时定位间隔,支持位置变化请求更新的
		option.setAddrType("all");            //是否需要地址信息
		mLocationClient.setLocOption(option);
		
		//位置监听，更新位置
		mLocationClient.registerLocationListener(new BDLocationListener() {
			public void onReceiveLocation(BDLocation location) {
				if (location == null)
					return;
				setLocation(location);
				
				switch (location.getLocType()) {
				case GPS_LOC:// GPS定位结果
					isLocated = true;
					if (!mIsGps) {
						mIsGps = true;
					}
					
					if (mGetLocation != null)
						mGetLocation.successful(location);
					break;
				case NET_LOC:// 表示网络定位结果
					isLocated = true;
					if (mIsGps) {
						mIsGps = false;
					}
					
					if (mGetLocation != null)
						mGetLocation.successful(location);

					break;

				case 62:// 扫描整合定位依据失败。此时定位结果无效。
				case 63:// 网络异常，没有成功向服务器发起请求。此时定位结果无效。
				case 65:
				case 162:// 服务端定位失败
				case 163:
				case 164:
				case 165:
				case 166:
				case 167:
				default: // 其它不明
					if (mGetLocation != null)
						mGetLocation.failure();
					//logE("Location  Error!!!!" + location.getLocType());
					
				}
				
				//log("BaiduLocation==registerLocationListener"+ location.getAddrStr() + 
				//		"," + location.getLongitude()+ "," + location.getLatitude());
			}

			public void onReceivePoi(BDLocation location) {
				// return ;
			}
		});
	}
	
	//有位置时通知提醒，开始发送短信
	public void elederStartAddress(Context context, String action) {
		Intent iten = new Intent(action);
		context.sendBroadcast(iten);
		log("注意次数,Send=Bro==>" + action);
	}

	// 开始定位
	public void startLocation(Boolean startTimer,int delay) {
		if (mLocationClient == null)
			return;
		if (!mLocationClient.isStarted()) {
			mLocationClient.start();
			
		}
		if(startTimer){//开放给别人用
			mStopThread = false;
			locationHand.postDelayed(thread, delay * 1000);
		}
	}
	public boolean isStarted() {
		
		return mLocationClient==null?false:mLocationClient.isStarted();
	}
	// 停止定位
	public void stopLocation(Boolean stopTimer) {
		if (mLocationClient == null)
			logE("mLocationClient==null");
		
		if (mLocationClient != null && mLocationClient.isStarted()) {
			mLocationClient.stop();
			logE("stop!");
		}
		
		if(stopTimer){
			mStopThread = true;
			locationHand.removeCallbacks(thread);
		}
		log("停止定位====mLocationClient.stop()");
	}

	public BDLocation getLocation() {
		return location;
	}

	public void setLocation(BDLocation location) {
		this.location = location;
	}
	
	// 判断经纬度是否有效
	public boolean judgeLegalLatlong() {
		
		double myLng = getLocation().getLongitude();
		double myLat = getLocation().getLatitude();

		if (isLocationValid(myLng, myLat)) {
			return true;
		}
		return false;
	}
	
	
	// 判断定位方式，1是Gps，0是网络定位,-1是未定位,其他的
	public int judgeLocationWay() {
		if (isLocated) {
			if (mIsGps)
				return 1;
			else
				return 0;
		} else {
			return -1;
		}
	}
	
	
	Handler locationHand = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == STOPTIMER) {
				if(mGetLocation!=null)
					mGetLocation.overTimeDo();
			}
			super.handleMessage(msg);
		}
	};

	Thread thread = new Thread() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			if (mStopThread)
				return;
			 locationHand.handleMessage(locationHand.obtainMessage(STOPTIMER));
		}
	};
	
	
	// 判断经纬度是否有效『静态方法』(可做校准后的判断)
	// 0,0 86,28 无效
	private static double DIFF = 0.1f;
	
	public static boolean isLocationValid(double lng, double lat) {
		if (isInRange(lng, 0, DIFF) && isInRange(lat, 0, DIFF)) {
			return false;
		}

		if (isInRange(lng, 86.0f, DIFF) && isInRange(lat, 28.0f, DIFF)) {
			return false;
		}

		if (!isJingRange(lng) || !isweiRange(lat)) {
			return false;
		}

		return true;
	}

	private static boolean isJingRange(double lng_org) {
		if (-180 <= lng_org && lng_org <= 180) {
			return true;
		}
		return false;
	}

	private static boolean isweiRange(double lat_org) {
		if (-90 <= lat_org && lat_org <= 90) {
			return true;
		}
		return false;
	}

	private static boolean isInRange(double in_value, double mid_value, double diff) {
		if ((in_value > (mid_value - diff)) && (in_value < (mid_value + diff))) {
			return true;
		}

		return false;
	}
	public void distory(){
		if(mLocationClient!=null){
			mLocationClient = null;
		}
	}
	public static void log(String msg) {
		LogUtils.logD("TAG",msg);
	}

	public static void logE(String msg) {
		LogUtils.logE("TAG",msg);
	}
}